<?php
/**
 * Created by PhpStorm.
 * Author: QinShuai
 * Email: qinshuai0423@qq.com
 * Date: 2021/6/14
 */

namespace backend\traits;

use Yii;
use yii\db\Exception;
use yii\helpers\ArrayHelper;

trait Controller
{
    /**
     * 首页
     * @param string $table
     * @return mixed
     */
    public function actionIndex($table = '')
    {
        $model = $this->getModel($table);
        $map = $this->search($model);
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }
        $data = $this->getList($model, $map);
        if (Yii::$app->request->isAjax) {
            return $this->success($data);
        }
        return $this->render('index');

    }

    /**
     * 删除
     * @return mixed
     * @throws Exception
     */
    public function actionDelete()
    {
        $ids = \Yii::$app->request->post('ids');
        $model = $this->getModel();
        $result = \Yii::$app->db->createCommand()
            ->update($model::tableName(), ['isdelete' => 1], ["id" => $ids])
            ->execute();
        if (!$result) {
            return $this->error('删除失败');
        }
        return $this->success();
    }

    /**
     * 永久删除
     * @return mixed
     */
    public function actionDeleteForever()
    {
        $ids = \Yii::$app->request->post('ids');
        $ids = explode(',', $ids);
        $model = $this->getModel();
        $result = $model::deleteAll(['id' => $ids]);
        if (!$result) {
            return $this->error('删除失败');
        }
        return $this->success();
    }

    /**
     * 添加/编辑
     * @return mixed
     */
    public function actionSave()
    {
        $model = $this->getModel();
        if (!Yii::$app->request->isPost) {
            return $this->error('请求方式错误！');
        }
        $data = \Yii::$app->request->post();
        if (!empty($data['id'])) {
            $model = $model::findOne($data['id']);
        }
        //重写参数值
        foreach ($data as $k => $val) {
            $key = str_replace(' ', '', ucwords(str_replace('_', ' ', $k)));
            if (method_exists($model, 'set' . $key)) {
                call_user_func([$model, 'set' . $key], $val);
                unset($data[$k]);
            }
        }
        //添加额外参数
        if (method_exists($model, '_additionalData')) {
            call_user_func([$model, '_additionalData'], $data);
        }
        //验证数据
        if (!$model->load($data, '') || !$model->validate()) {
            return $this->error($model->errors[0]);
        }
        if (method_exists($model, '_beforeSave')) {
            call_user_func([$model, '_beforeSave'], $model);
        }
        if (!$model->save()) {
            return $this->error('操作失败');
        }
        if (method_exists($model, '_afterSave')) {
            call_user_func([$model, '_afterSave'], $model);
        }
        $model = ArrayHelper::toArray($model);
        return $this->success(['row' => $model], 'success');
    }

}